<template>
	<div class="table-box">
		<proTable
			ref="proTableRef"
			:columns="columns"
			:toolButton="true"
			:requestApi="competitionApi.GetCompetitionPageListApi"
			:initParam="initParam"
			:dataCallback="dataCallback"
			:searchCol="{ xs: 1, sm: 2, md: 2, lg: 3, xl: 4 }"
		>
			<template #tableHeader>
				<Authority :permission="['competiton:set', 'competiton:get']">
					<el-button type="primary" :icon="CirclePlus" @click="openDrawer('新增')">添加赛事</el-button>
				</Authority>
			</template>
			<template #operation="scope">
				<el-space wrap>
					<el-tag v-if="scope.row.state !== 6" style="cursor: pointer" @click="openDrawer('编辑', scope.row)"> 编辑 </el-tag>
					<el-tag
						style="cursor: pointer"
						@click="handleSave(scope.row)"
						v-if="scope.row.state > 0 && scope.row.state < 6"
						:type="scope.row.state == 1 ? 'success' : 'warning'"
					>
						{{ scope.row.state == 1 ? "发布" : "关闭赛事" }}
					</el-tag>
					<el-tag style="cursor: pointer" @click="handleClose(scope.row)" v-if="scope.row.state == 1" type="warning">
						关闭赛事
					</el-tag>
					<el-tag v-if="scope.row.state > 1 || scope.row.state < 0" @click="getQRCode(scope.row)" style="cursor: pointer">
						二维码
					</el-tag>
					<el-tag v-if="scope.row.state > 1 || scope.row.state < 0" @click="setReferee(scope.row)" style="cursor: pointer">
						裁判员
					</el-tag>
					<el-tag @click="handleRaces(scope.row)" style="cursor: pointer" type="info"> 比赛项目 </el-tag>
				</el-space>
			</template>
			<template #merchants="scope">
				{{ scope.row.merchants }}
			</template>
		</proTable>
		<el-dialog v-model="codeShow" width="30%" title="赛事二维码">
			<el-row>
				<el-col :span="24">
					<h3 style="text-align: center">
						{{ qrcode.competitionName }}
					</h3>
				</el-col>
			</el-row>
			<el-row>
				<el-col style="display: flex; justify-content: center; margin: 15px auto" :span="24">
					<qrcode-vue :value="qrcode.url" :size="300" level="H" />
				</el-col>
			</el-row>
			<el-row :gutter="20">
				<el-col :span="12" :offset="6">
					<p style="margin: 15px 0; text-align: center">扫一扫进入赛事详情页</p>
				</el-col>
			</el-row>
		</el-dialog>
		<el-dialog width="70%" @close="closeDialogRerefee" v-model="dialogRerefee" title="赛事裁判列表">
			<template #default>
				<el-dialog v-model="innerVisible" width="60%" @close="closeInnerViseble" title="新增裁判" append-to-body>
					<proTable
						ref="refereeTableRef"
						:columns="refereeColumns"
						:toolButton="false"
						:requestApi="api.GetAllRefereeListApi"
						:initParam="refereeParam"
						:dataCallback="refereeCallback"
						:pagination="false"
					>
					</proTable>
					<template #footer>
						<el-button @click="closeInnerViseble">取消</el-button>
						<el-button type="primary" @click="handleCrushRefereeClick"> 确认 </el-button>
					</template>
				</el-dialog>
				<el-button style="margin: 15px 0" type="primary" :icon="CirclePlus" @click="innerVisible = true">添加裁判</el-button>
				<el-table ref="multipleTableRef" :data="compotetionRerefee" style="width: 100%" @selection-change="handleSelectionChange">
					<el-table-column type="selection" width="55" />
					<el-table-column property="name" label="姓名" />
					<el-table-column property="phone" label="电话号码" />
				</el-table>
			</template>
			<template #footer>
				<el-button @click="closeDialogRerefee">取消</el-button>
				<el-button type="primary" @click="handleDeleteRefereeClick"> 删除所选裁判员 </el-button>
			</template>
		</el-dialog>
		<eventDrawer ref="drawerRef" />
	</div>
</template>
<script lang="ts" setup name="logs">
import { ref, reactive, computed } from "vue";
import companyInfoApi from "@/api/modules/paymentOrderInfo";
import competitionApi from "@/api/modules/competition";
import api from "@/api/modules/referee";
import { useRouter } from "vue-router";
import { ColumnProps } from "@/components/ProTable/interface";
import { useHandleData } from "@/hooks/useHandleData";
import proTable from "@/components/ProTable/index.vue";
import { CirclePlus } from "@element-plus/icons-vue";
import QrcodeVue from "qrcode.vue";
import { GlobalStore } from "@/stores";
import eventDrawer from "./components/eventDrawer.vue";
import { ElMessage, ElTable } from "element-plus";
// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTableRef = ref();
const refereeTableRef = ref();
const multipleTableRef = ref<InstanceType<typeof ElTable>>();
const dialogRerefee = ref<boolean>(false);
const innerVisible = ref<boolean>(false);
const globalStore = GlobalStore();
const compotetionRerefee = ref<any[]>([]);
const delRerefeeIds = ref<any[]>([]);
const compotetionId = ref<string>("");
// 路由对象
const router = useRouter();
// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({
	Order: "", //排序方式，默认DESC
	Sort: "" //排序字段，默认CreateTime
});
const refereeParam = reactive({
	name: "", //姓名
	phone: "" //手机号码
});
const refereeCallback = (data: any) => {
	return data.data;
};
// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 datalist && total && pageNum && pageSize 这些字段，那么你可以在这里进行处理成这些字段
const dataCallback = (data: any) => {
	return {
		list: data.data,
		total: data.totalCount
	};
};
// 商户选项
const getCompanysList = async () => {
	let { result } = await companyInfoApi.GetCompanysList();
	let { data } = result as any;
	data.unshift({ companyName: "全部", id: "" });
	return result;
};

// 搜索菜单结束时间一定要大于开始时间
const gameDisablesDate = (time: any) => {
	let gameBeginTime = proTableRef.value?.searchParam.gameBeginTime;
	if (!gameBeginTime) {
		return false;
	}
	const _minTime = new Date(gameBeginTime).getTime();
	return time.getTime() < _minTime;
};
const signDisablesDate = (time: any) => {
	let signBeginTime = proTableRef.value?.searchParam.signBeginTime;
	if (!signBeginTime) {
		return false;
	}
	const _minTime = new Date(signBeginTime).getTime();
	return time.getTime() < _minTime;
};
// 搜索菜单开始时间一定小雨开始时间
const gameStartDisablesDate = (time: any) => {
	let gameEndTime = proTableRef.value?.searchParam.gameEndTime;
	if (!gameEndTime) {
		return false;
	}
	const _minTime = new Date(gameEndTime).getTime();
	return time.getTime() > _minTime;
};
const signStartDisablesDate = (time: any) => {
	let signEndTime = proTableRef.value?.searchParam.signEndTime;
	if (!signEndTime) {
		return false;
	}
	const _minTime = new Date(signEndTime).getTime();
	return time.getTime() > _minTime;
};
const selectable = (row: any): boolean => {
	if (!compotetionRerefee.value.length) {
		return true;
	}
	return compotetionRerefee.value.every(i => i.idNumber !== row.idNumber);
};

// 表格配置项
const columns = computed((): Partial<ColumnProps>[] => {
	let data: Partial<ColumnProps>[] = [
		{ prop: "name", label: "赛事名称", search: { el: "input" } },
		{
			prop: "merchants",
			label: "所属商户",
			enum: getCompanysList,
			search: { el: "select" },
			fieldNames: { label: "companyName", value: "id" }
		},
		{ prop: "hostUnit", label: "主办方" },
		{ prop: "address", label: "举办地点" },
		{ prop: "detailsAddress", label: "详细地址" },
		{ prop: "projectCount", label: "比赛项目数" },
		{ prop: "signTime", label: "报名时间" },
		{ prop: "signPeopleCount", label: "报名人数" },
		{ prop: "matchTime", label: "比赛时间" },
		// { prop: "stateStr", label: "状态", tag: true },
		{
			prop: "state",
			label: "状态",
			isShow: true,
			tag: true,
			// （-1：全部；0：关闭；1：待发布；2：报名未开始；3：正在报名；4：报名结束待比赛；5：正在比赛；6：比赛结束）
			enum: [
				{
					label: "全部",
					value: -1
				},
				{
					label: "已关闭",
					value: 0
				},
				{
					label: "待发布",
					value: 1
				},
				{
					label: "报名未开始",
					value: 2
				},
				{
					label: "正在报名",
					value: 3
				},
				{
					label: "待比赛",
					value: 4
				},
				{
					label: "正在比赛",
					value: 5
				},
				{
					label: "比赛结束",
					value: 6
				}
			],
			search: { el: "select" }
		},
		{
			prop: "keyWords",
			label: "关键字",
			isShow: false,
			search: { el: "input", props: { placeholder: "请输入赛事名称/主办方/举办地址" } }
		},
		{
			prop: "city",
			label: "举办城市",
			isShow: false,
			search: { el: "input" }
		},
		{
			prop: "gameBeginTime",
			label: "比赛开始时间",
			isShow: false,
			search: { el: "date-picker", props: { type: "date", ["value-format"]: "YYYY-MM-DD", disabledDate: gameStartDisablesDate } }
		},
		{
			prop: "gameEndTime",
			label: "比赛结束时间",
			isShow: false,
			search: { el: "date-picker", props: { type: "date", ["value-format"]: "YYYY-MM-DD", disabledDate: gameDisablesDate } }
		},
		{
			prop: "signBeginTime",
			label: "报名开始时间",
			isShow: false,
			search: { el: "date-picker", props: { type: "date", ["value-format"]: "YYYY-MM-DD", disabledDate: signStartDisablesDate } }
		},
		{
			prop: "signEndTime",
			label: "报名结束时间",
			isShow: false,
			search: { el: "date-picker", props: { type: "date", ["value-format"]: "YYYY-MM-DD", disabledDate: signDisablesDate } }
		},
		{ prop: "operation", label: "操作", align: "left", width: 370, fixed: "right" }
	];
	if (globalStore.isPlatform) {
		return (data = data.filter(i => i.prop !== "merchants"));
	}
	return data;
});
const refereeColumns: Partial<ColumnProps>[] = [
	{ type: "selection", width: 60, selectable, fixed: "left" },
	{
		prop: "name",
		label: "姓名",
		search: { el: "input", props: { placeholder: "请输入姓名" } }
	},
	{ prop: "phone", label: "手机号", search: { el: "input", props: { placeholder: "请输入手机号" } } },
	{ prop: "idNumber", label: "身份证" }
];
// 发布，关闭赛事等操作
const handleSave = async (res: any) => {
	let bool = res.state == 1;
	let str = bool ? "发布赛事" : "关闭赛事";
	if (bool) {
		await useHandleData(competitionApi.ReleaseCompetitionApi, res.id, `${str + res.name}吗`);
		proTableRef.value.getTableList();
	} else {
		await useHandleData(competitionApi.CloseCompetitionApi, res.id, `${str + res.name}吗`);
		proTableRef.value.getTableList();
	}
};
const handleClose = async (res: any) => {
	await useHandleData(competitionApi.CloseCompetitionApi, res.id, `${"关闭赛事" + res.name}吗`);
	proTableRef.value.getTableList();
};
// 打开二维码
const codeShow = ref<boolean>(false);
const qrcode = ref<any>({
	url: "",
	competitionName: ""
});
const competetionReferee = ref<any>({
	id: "",
	competetionId: ""
});
// 获取二维码
const getQRCode = (row: any) => {
	if (row.projectCount == 0) {
		alert("没有项目，暂时无法在移动端查看赛事详情");
		return;
	}
	codeShow.value = true;
	qrcode.value.url = row.qrCodeUrl;
	qrcode.value.competitionName = row.name;
};
// 跳转到比赛项目
const handleRaces = (row: any) => {
	router.push({
		path: "/competition/eventProject",
		query: {
			id: row.id
		}
	});
};
// 绑定裁判员
const setReferee = async (row: any): Promise<void> => {
	compotetionRerefee.value.length = 0;
	dialogRerefee.value = true;
	competetionReferee.value.competetionId = row.id;
	compotetionId.value = row.id!;
	let { result } = await api.GetRefereeListByCompetitionIdApi({ CompetitionId: row.id });
	if (result.code !== 200) return;
	compotetionRerefee.value = result.data;
};
const handleCrushRefereeClick = async (): Promise<void> => {
	if (!refereeTableRef.value?.selectedListIds.length) {
		ElMessage.error("请选择裁判人员");
		return;
	}
	let params = {
		refereeIds: refereeTableRef.value?.selectedListIds,
		competitionId: competetionReferee.value.competetionId
	};
	await api.AddRefereeCompetitionApi(params);
	let { result } = await api.GetRefereeListByCompetitionIdApi({ CompetitionId: compotetionId.value });
	if (result.code !== 200) return;
	compotetionRerefee.value = result.data;
	closeInnerViseble();
	ElMessage.success("添加裁判员成功！");
};

const closeInnerViseble = (): void => {
	refereeTableRef.value!.clearSelection();
	innerVisible.value = false;
};
const closeDialogRerefee = (): void => {
	multipleTableRef.value!.clearSelection();
	compotetionRerefee.value.length = 0;
	dialogRerefee.value = false;
};
// 删除裁判员的判定
const handleDeleteRefereeClick = async (): Promise<void> => {
	if (!delRerefeeIds.value.length) {
		ElMessage.error("请选择裁判人员");
		return;
	}
	await api.DeleteRefereeCompetitionApi({ ids: delRerefeeIds.value });
	let { result } = await api.GetRefereeListByCompetitionIdApi({ CompetitionId: compotetionId.value });
	compotetionRerefee.value.length = 0;
	if (result.code !== 200) return;
	compotetionRerefee.value = result.data;
};
const handleSelectionChange = (val: any): void => {
	delRerefeeIds.value = val.map((item: any) => item.id);
};
// 打开 drawer(新增、查看、编辑)
const drawerRef = ref<InstanceType<typeof eventDrawer> | null>(null);
const openDrawer = (title: string, row: any | null = null) => {
	const params = {
		title,
		isView: title === "查看",
		row,
		api: undefined,
		getTableList: proTableRef.value.getTableList
	};
	drawerRef.value?.acceptParams(params);
};
</script>
<style lang="scss">
.el-table .warning-row,
.el-table .warning-row .el-table-fixed-column--right,
.el-table .warning-row .el-table-fixed-column--left {
	background-color: var(--el-color-warning-light-9);
}
.el-table .success-row,
.el-table .success-row .el-table-fixed-column--right,
.el-table .success-row .el-table-fixed-column--left {
	background-color: var(--el-color-success-light-9);
}
</style>
